#coding=utf8
'''
Created on 2016年6月11日

@author: zhangjinrui
'''

import os
import json
import time
import sys

class DataReader:
    
    def __init__(self, path):
        self.folder_path = path
        self.files = []
        self.file_readers = {}
        
        files = os.listdir(self.folder_path)
        for f in files:
            if (os.path.isfile(self.folder_path + '/' + f)) and f[0] != '.':
                #将文件添加到列表
                self.files.append(f)
                fr = open(self.folder_path + '/' + f, 'r')
                hostname = self.get_file_name_without_ext(f)
                
                #保存文件指针
                self.file_readers[hostname] = fr
                
        self.align_file_start()
    
    #用来校准所有数据的起始时间
    def align_file_start(self):
        print '文件打开结束，开始对齐数据'
        max_time_stamp = -1
        #先找出最大的时间戳
        for k,fr in self.file_readers.items():
            line = fr.readline()
            data = json.loads(line)
            if data['timestamp'] > max_time_stamp:
                max_time_stamp = data['timestamp']
        
        print('最大时间为：%s' %(self.get_format_time(max_time_stamp)))
        #然后每个文件依次进行调整
        for k,fr in self.file_readers.items():
            data = json.loads(fr.readline())
            while abs(data['timestamp'] - max_time_stamp) > 2:
                line = fr.readline()
                if line == '':
                    break
                data = json.loads(line)
    
    def get_one_set_data(self):
        dat = {}
        for k,fr in self.file_readers.items():
            #如果有一个文件已经到了末尾，则直接结束
            s = fr.readline()
            if s == '':
                return None
            one_row_data = json.loads(s)
            dat[k] = one_row_data
        return dat
    
    def get_format_time(self,t):
        t = time.localtime(t)
        return time.strftime('%Y-%m-%d %H:%M:%S',t) 
    
    def close_all_file(self):
        for k,fr in self.file_readers.items():
            fr.close()
    
    def get_file_name_without_ext(self, fname):
        idx = fname.rindex('.')
        return fname[:idx]
        
    def get_file_list(self):
        return self.files
            
    def get_host_count(self):
        return len(self.files)
    
    def get_hostnames(self):
        return self.file_readers.keys()
    

if __name__ == '__main__':
    dr = DataReader('../../data')
    print dr.get_format_time(time.time())
        
